package com.eva.framework.captcha.image;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

@Data
@Schema(description = "图片验证码")
public class ImageCaptcha {

    @Schema(description = "验证码UUID")
    private String uuid;

    @JsonIgnore
    @Schema(description = "验证码", hidden = true)
    private String text;

    @Schema(description = "验证码Base64")
    private String image;

    public ImageCaptcha(String text, BufferedImage image) {
        this.uuid = UUID.randomUUID().toString();
        this.text = text;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", stream);
        } catch (IOException e) {
            throw new RuntimeException("build captcha throw an exception", e);
        }
        this.image = "data:image/png;base64," + Base64.getEncoder().encodeToString(stream.toByteArray());
    }
}
